package cn.tips.dmp.common.sms.captcha.controller;

import cn.tips.dmp.common.sms.captcha.service.CaptchaService;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 短信操作
 *
 * @author pkb
 */
@RestController
@RequestMapping("/tipsApi/common/captcha")
@Slf4j
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Producer producer;


    @RequestMapping("/getImgCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        String captchaText = producer.createText();
        String key = captchaService.getImgCaptchaKey(request);
        // 十分钟过期
        stringRedisTemplate.opsForValue().set(key,captchaText,5, TimeUnit.MINUTES);
        BufferedImage image = producer.createImage(captchaText);
        ServletOutputStream outputStream=null;
        try {
            outputStream= response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/checkImgCaptcha")
    public String check(HttpServletRequest request, HttpServletResponse response, @RequestParam String value){
        String key = captchaService.getImgCaptchaKey(request);
        String v = stringRedisTemplate.opsForValue().get(key);
        if (v.equals(value)){
            return "验证成功";
        }else {
            return "校验失败";
        }
    }

}
